// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  
  console.log('客服云函数被调用，参数：', event)
  
  try {
    // 获取用户信息
    const userOpenId = wxContext.OPENID
    const userUnionId = wxContext.UNIONID
    const userAppId = wxContext.APPID
    
    // 构建客服消息
    const message = {
      touser: userOpenId,
      msgtype: 'text',
      text: {
        content: '你好！我是华声康护的客服助手，很高兴为您服务。请问有什么可以帮助您的吗？'
      }
    }
    
    // 发送客服消息
    const result = await cloud.openapi.customerServiceMessage.send(message)
    
    console.log('客服消息发送结果：', result)
    
    return {
      success: true,
      message: '客服消息发送成功',
      data: {
        userOpenId: userOpenId,
        userUnionId: userUnionId,
        userAppId: userAppId,
        messageContent: message.text.content,
        sendResult: result,
        timestamp: new Date().toISOString()
      },
      timestamp: Date.now()
    }
    
  } catch (error) {
    console.error('客服消息发送失败：', error)
    
    return {
      success: false,
      message: '客服消息发送失败',
      error: error.message,
      data: {
        userOpenId: wxContext.OPENID,
        timestamp: new Date().toISOString()
      },
      timestamp: Date.now()
    }
  }
} 